package cn.dong.edu.service.impl;

import cn.dong.edu.domain.Subject;
import cn.dong.edu.domain.dto.SubjectRecordVo;
import cn.dong.edu.domain.dto.SubjectVo;
import cn.dong.edu.mapper.SubjectMapper;
import cn.dong.edu.service.SubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author You-Dong
 * @since 2021-02-04
 */
@Service
@Transactional
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    /**
     * 科目分类，excel导入到数据库
     *
     * @return
     */
    @Override
    public SubjectRecordVo importSubject(MultipartFile file) {
        // 创建结果集
        SubjectRecordVo sub = new SubjectRecordVo();
        sub.setMessage(new ArrayList<String>());
        List<String> messages = sub.getMessage();
        try {
            // 获取文件
            InputStream in = file.getInputStream();

            // 读取工作空间,使用07版本的
            Workbook workbook = new XSSFWorkbook(in);
            // 非空判断
            if (workbook == null) {
                messages.add("文件为空，或不是xlsx文件");
                return sub;
            }
            // 获取Sheet
            Sheet sheet = workbook.getSheetAt(0);
            // 获取最后一个行
            int lastRowNum = sheet.getLastRowNum();
            // 循环读取
            for (int i = 1; i <= lastRowNum; i++) {
                Row row = sheet.getRow(i);
                // 为空判断
                if (row == null) {
                    sub.setNullRow(sub.getNullRow() + 1);
                    messages.add("第" + (i + 1) + "行为空\n");
                    continue;
                }
                // 获取行中的列,已知2个列，一级分类和二级分类
                Cell cell1 = row.getCell(0);
                // 非空判断
                if (cell1 == null) {
                    sub.setNullCell(sub.getNullCell() + 1);
                    messages.add("第" + (i + 1) + "行,第一列为空！\n");
                    continue;
                }
                // 一级分类，父id，0代表没有
                String type1 = cell1.getStringCellValue();
                Subject subject1 = this.existTypeCreate(type1, "0", sub);


                // 二级分类，创建二级分类需要一级分类的父id
                Cell cell2 = row.getCell(1);
                // 非空判断
                if (cell2 == null) {
                    sub.setNullCell(sub.getNullCell() + 1);
                    messages.add("第" + (i + 1) + "行,第二列为空！");
                    continue;
                }
                String type2 = cell2.getStringCellValue();
                this.existTypeCreate(type2, subject1.getId(), sub);
            }

        } catch (IOException e) {
            log.error(e.getMessage());
        }

        return sub;
    }

    /**
     * 查询全部科目
     * @return
     */
    @Override
    public List<SubjectVo> findAll() {
        // 结果
        List<SubjectVo> subjectVos = new ArrayList<SubjectVo>(20);
        // 查询全部的一级科目列表
        QueryWrapper<Subject> war = new QueryWrapper<Subject>();
        war.eq("parent_id", "0");
        List<Subject> list = super.baseMapper.selectList(war);
        // 遍历该一级科目列表
        for (Subject subject : list) {
            // 根据这个一级科目，查询所有的二级科目
            QueryWrapper<Subject> query = new QueryWrapper<Subject>();
            query.eq("parent_id", subject.getId());
            // 所有的二级科目的sub转换为subVo
            List<Subject> subjects = super.baseMapper.selectList(query);
            System.out.println(subjects);
            List<SubjectVo> vos = new ArrayList<SubjectVo>(20);
            for (Subject sub : subjects) {
                // 没有三级科目
                vos.add(new SubjectVo(sub.getTitle(), sub.getId(), null));
            }
            // 创建树形实体，增加到结果
            SubjectVo subjectVo = new SubjectVo(subject.getTitle(), subject.getId(), vos);
            subjectVos.add(subjectVo);
        }
        return subjectVos;
    }

    /**
     * 根据二级科目id，查询一级科目id
     *
     * @param id
     * @return
     */
    @Override
    public String findOneIdByTwo(String id) {
        QueryWrapper<Subject> query = new QueryWrapper<Subject>();
        query.eq("id", id);
        query.select("parent_id");
        Subject subject = super.baseMapper.selectOne(query);
        return subject.getParentId();
    }

    /**
     * 是否存在科目，存在则创建
     */
    private Subject existTypeCreate(String type, String parentId, SubjectRecordVo sub) {
        // 获取信息列表
        List<String> messages = sub.getMessage();
        // 查询该一级分类是否出现重复
        QueryWrapper<Subject> query = new QueryWrapper<Subject>();
        query.eq("title", type);
        query.eq("parent_id", parentId);
        Subject subject = super.baseMapper.selectOne(query);
        if (subject == null) {
            // 数据库中不存在此数据，可以添加
            Subject set = new Subject();
            set.setTitle(type);
            set.setParentId(parentId);
            set.setSort(0);
            // 增加到数据库中
            super.baseMapper.insert(set);
            // 判断科目
            if ("0".equals(parentId)) {
                messages.add(type + ",一级科目添加成功!\n");
                sub.setOneSucCount(sub.getOneSucCount() + 1);
            } else {
                messages.add(type + ",二级科目添加成功!\n");
                sub.setTwoSucCount(sub.getTwoSucCount() + 1);
                sub.setSucCount(sub.getSucCount() + 1);
            }
            // 返回sub
            return set;
        } else {
            if ("0".equals(parentId)) {
                messages.add(type + ",该一级科目已经存在了!\n");
                sub.setOneReCount(sub.getOneReCount() + 1);
                sub.setReCount(sub.getReCount() + 1);
            } else {
                messages.add(type + ",该二级科目已经存在了!\n");
                sub.setTwoReCount(sub.getTwoReCount() + 1);
                sub.setReCount(sub.getReCount() + 1);
            }
        }
        return subject;
    }



}
